<template>
  <view class="order-detail-page">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <scroll-view class="content-scroll" scroll-y v-else>
      <!-- 订单状态卡片 -->
      <view class="status-card" :class="orderInfo.statusClass">
        <view class="status-icon-wrapper">
          <view class="status-icon">
            <text class="icon-text">{{ getStatusIcon(orderInfo.status) }}</text>
          </view>
        </view>
        <view class="status-info">
          <text class="status-title">{{ orderInfo.statusText }}</text>
          <text class="status-desc">{{ getStatusDesc(orderInfo.status) }}</text>
        </view>
      </view>

      <!-- 物流信息卡片 -->
      <view class="logistics-card" v-if="orderInfo.status === 'shipped' || orderInfo.status === 'completed'">
        <view class="card-header">
          <text class="card-title">物流信息</text>
          <text class="logistics-company">{{ orderInfo.logistics.company }}</text>
        </view>
        <view class="logistics-content">
          <view class="logistics-number">
            <text class="label">运单号：</text>
            <text class="number">{{ orderInfo.logistics.trackingNumber }}</text>
            <view class="copy-btn" @click="copyTrackingNumber" :style="{background: themeColorStyles.primaryColorBg, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
              <text class="copy-text" :style="{color: themeColorStyles.primaryColor}">复制</text>
            </view>
          </view>

          <!-- 查看详情按钮 -->
          <view class="logistics-detail-btn" @click="showLogisticsDetail" :style="{background: themeColorStyles.primaryColorBg, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
            <text class="detail-btn-text" :style="{color: themeColorStyles.primaryColor}">查看物流详情</text>
            <text class="detail-btn-arrow" :style="{color: themeColorStyles.primaryColor}">></text>
          </view>
        </view>
      </view>

      <!-- 收货地址卡片 -->
      <view class="address-card">
        <view class="card-header">
          <text class="card-title">收货地址</text>
          <view class="change-address-btn" v-if="orderInfo.canChangeAddress" @click="openAddressModal" :style="{background: themeColorStyles.primaryColorBg, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
            <text class="change-text" :style="{color: themeColorStyles.primaryColor}">更换地址</text>
          </view>
        </view>
        <view class="address-content">
          <view class="address-info">
            <view class="recipient-info">
              <text class="recipient-name">{{ orderInfo.address.name }}</text>
              <text class="recipient-phone">{{ orderInfo.address.phone }}</text>
            </view>
            <text class="address-detail">{{ orderInfo.address.detail }}</text>
          </view>
          <view class="address-icon">
            <text class="icon">📍</text>
          </view>
        </view>
      </view>

      <!-- 商品信息卡片 -->
      <view class="goods-card">
        <view class="card-header">
          <text class="card-title">商品信息</text>
          <text class="goods-count">{{ orderInfo.goodsList.length }}件商品</text>
        </view>
        <view class="goods-list">
          <view class="goods-item" v-for="goods in orderInfo.goodsList" :key="goods.id">
            <view class="goods-image-wrapper">
              <image class="goods-image" :src="goods.skuImage || goods.image" mode="aspectFill" />
            </view>
            <view class="goods-info">
              <text class="goods-name">{{ goods.skuName || goods.name || goods.productName || goods.realProductName ||
                '未知商品' }}</text>
              <text class="goods-spec" v-if="goods.spec">{{ goods.spec }}</text>
              <view class="goods-price-qty">
                <text class="goods-price" :style="{color: themeColorStyles.primaryColor}">¥{{ goods.price }}</text>
                <text class="goods-qty">×{{ goods.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 优惠券卡片 -->
      <view class="coupon-card">
        <view class="card-header">
          <text class="card-title">优惠券</text>
          <view class="coupon-action" :class="{ disabled: orderInfo.orderStatus != 1 }"
            @click="orderInfo.orderStatus == 1 ? showCouponSelection() : null">
            <text class="coupon-text" v-if="!getUsedCouponInfo() && !selectedCoupon">{{ orderInfo.orderStatus == 1 ?
              '选择优惠券' : '未使用优惠券' }}</text>
            <text class="coupon-text selected" v-else-if="selectedCoupon">{{ getCouponDisplayText(selectedCoupon)
              }}</text>
            <text class="coupon-text selected" v-else-if="getUsedCouponInfo()">{{ getUsedCouponInfo().couponName ||
              '已使用优惠券' }}</text>
            <text class="arrow-icon" v-if="orderInfo.orderStatus == 1">></text>
          </view>
        </view>
        <view class="coupon-info" v-if="selectedCoupon || getUsedCouponInfo()">
          <text class="coupon-desc" v-if="selectedCoupon">{{ getCouponDescription(selectedCoupon) }}</text>
          <text class="coupon-desc" v-else-if="getUsedCouponInfo()">{{ getCouponDescription(getUsedCouponInfo())
            }}</text>
          <text class="coupon-discount" v-if="selectedCoupon">-¥{{ getCouponDiscountAmount(selectedCoupon) }}</text>
          <text class="coupon-discount" v-else-if="getUsedCouponInfo() && orderInfo.couponAmount">-¥{{
            parseFloat(orderInfo.couponAmount).toFixed(2) }}</text>
        </view>
      </view>

      <!-- 订单信息卡片 -->
      <view class="order-info-card">
        <view class="card-header">
          <text class="card-title">订单信息</text>
        </view>
        <view class="order-details">
          <view class="detail-item">
            <text class="detail-label">订单号</text>
            <view class="detail-value-wrapper">
              <text class="detail-value">{{ orderInfo.orderNo }}</text>
              <view class="copy-btn" @click="copyOrderNo" :style="{background: themeColorStyles.primaryColorBg, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
                <text class="copy-text" :style="{color: themeColorStyles.primaryColor}">复制</text>
              </view>
            </view>
          </view>
          <view class="detail-item">
            <text class="detail-label">下单时间</text>
            <text class="detail-value">{{ orderInfo.createTime }}</text>
          </view>
          <view class="detail-item" v-if="orderInfo.payTime">
            <text class="detail-label">支付时间</text>
            <text class="detail-value">{{ orderInfo.payTime }}</text>
          </view>
          <view class="detail-item" v-if="orderInfo.shipTime">
            <text class="detail-label">发货时间</text>
            <text class="detail-value">{{ orderInfo.shipTime }}</text>
          </view>
        </view>
      </view>

      <!-- 费用明细卡片 -->
      <view class="cost-card">
        <view class="card-header">
          <text class="card-title">费用明细</text>
        </view>
        <view class="cost-details">
          <view class="cost-item">
            <text class="cost-label">商品总额</text>
            <text class="cost-value">¥{{ orderInfo.goodsAmount }}</text>
          </view>
          <view class="cost-item">
            <text class="cost-label">运费</text>
            <text class="cost-value">¥{{ orderInfo.shippingFee }}</text>
          </view>
          <view class="cost-item" v-if="getTotalDiscountAmount() > 0">
            <text class="cost-label">优惠金额</text>
            <text class="cost-value discount">-¥{{ getTotalDiscountAmount() }}</text>
          </view>
          <view class="cost-item total">
            <text class="cost-label">实付金额</text>
            <text class="cost-value total-price" :style="{color: themeColorStyles.primaryColor}">¥{{ getFinalAmount() }}</text>
          </view>
        </view>
      </view>

      <!-- 底部间距 -->
      <view class="bottom-space"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer-actions" v-if="hasActions">
      <view class="action-buttons">
        <view class="action-btn secondary" v-if="orderInfo.canCancel" @click="cancelOrder" :style="{background: themeColorStyles.primaryColorBg, color: themeColorStyles.primaryColor, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
          <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消订单</text>
        </view>
        <view class="action-btn primary" v-if="orderInfo.canPay" @click="payOrder" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
          <text class="btn-text">立即支付</text>
        </view>
        <view class="action-btn primary" v-if="orderInfo.canConfirm" @click="confirmOrder" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
          <text class="btn-text">确认收货</text>
        </view>
        <view class="action-btn primary" v-if="orderInfo.canEvaluate" @click="evaluateOrder" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
          <text class="btn-text">评价订单</text>
        </view>
        <view class="action-btn secondary" v-if="orderInfo.canRefund" @click="refundOrder" :style="{background: themeColorStyles.primaryColorBg, color: themeColorStyles.primaryColor, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
          <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">申请退款</text>
        </view>
      </view>
    </view>

    <!-- 支付方式选择弹窗 -->
    <view class="payment-modal" v-if="showPaymentModal" @click="closePaymentModal" :style="{'--primary-color': themeColorStyles.primaryColor, '--primary-color-rgb': themeColorStyles['--primary-color-rgb']}">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择支付方式</text>
          <view class="close-btn" @click="closePaymentModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="payment-methods">
          <view class="payment-item" :class="{ 'selected': selectedPayment === 'wechat' }"
            @click="selectPayment('wechat')">
            <view class="payment-icon">
              <image src="/static/wechat_pay.png" class="payment-icon-img"></image>
            </view>
            <view class="payment-info">
              <text class="payment-name">微信支付</text>
              <text class="payment-desc">安全便捷的支付方式</text>
            </view>
            <view class="payment-radio">
              <view class="radio-circle" :class="{ 'checked': selectedPayment === 'wechat' }">
                <view class="radio-dot" v-if="selectedPayment === 'wechat'"></view>
              </view>
            </view>
          </view>
        </view>

        <view class="payment-amount">
          <text class="amount-label">支付金额：</text>
          <text class="amount-value" :style="{color: themeColorStyles.primaryColor}">¥{{ getFinalAmount() }}</text>
        </view>

        <view class="modal-actions">
          <view class="cancel-btn" @click="closePaymentModal" :style="{background: themeColorStyles.primaryColorBg, color: themeColorStyles.primaryColor, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
            <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消</text>
          </view>
          <view class="confirm-btn" @click="confirmPayment" :class="{ 'disabled': !selectedPayment }" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
            <text class="btn-text">确认支付</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <view class="coupon-modal" v-if="showCouponModal" @click="closeCouponModal" :style="{'--primary-color': themeColorStyles.primaryColor}">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择优惠券</text>
          <view class="close-btn" @click="closeCouponModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="coupon-list">
          <!-- 加载状态 -->
          <view v-if="loadingCoupons" class="loading-state">
            <text class="loading-text">加载优惠券中...</text>
          </view>

          <!-- 无可用优惠券 -->
          <view v-else-if="availableCoupons.length === 0" class="empty-state">
            <text class="empty-text">暂无可用优惠券</text>
          </view>

          <!-- 不使用优惠券选项 -->
          <view class="coupon-item" :class="{ 'selected': !tempSelectedCoupon }" @click="selectCoupon(null)">
            <view class="coupon-info">
              <text class="coupon-title">不使用优惠券</text>
            </view>
            <view class="coupon-radio">
              <view class="radio-circle" :class="{ 'checked': !tempSelectedCoupon }">
                <view class="radio-dot" v-if="!tempSelectedCoupon"></view>
              </view>
            </view>
          </view>

          <!-- 优惠券列表 -->
          <view class="coupon-item"
            :class="{ 'selected': tempSelectedCoupon && tempSelectedCoupon.userCouponId === coupon.userCouponId, 'disabled': !isCouponAvailable(coupon) }"
            v-for="coupon in availableCoupons" :key="coupon.userCouponId" @click="selectCoupon(coupon)">
            <view class="coupon-info">
              <view class="coupon-header">
                <text class="coupon-title">{{ getCouponDisplayText(coupon) }}</text>
                <text class="coupon-type">{{ getCouponTypeText(coupon.couponType) }}</text>
              </view>
              <text class="coupon-desc">{{ getCouponDescription(coupon) }}</text>
              <text class="coupon-validity">有效期至：{{ formatDate(coupon.expireTime) }}</text>
            </view>
            <view class="coupon-radio">
              <view class="radio-circle"
                :class="{ 'checked': tempSelectedCoupon && tempSelectedCoupon.userCouponId === coupon.userCouponId }">
                <view class="radio-dot"
                  v-if="tempSelectedCoupon && tempSelectedCoupon.userCouponId === coupon.userCouponId"></view>
              </view>
            </view>
          </view>
        </view>

        <view class="modal-actions">
          <view class="cancel-btn" @click="closeCouponModal" :style="{background: themeColorStyles.primaryColorBg, color: themeColorStyles.primaryColor, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
            <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消</text>
          </view>
          <view class="confirm-btn" @click="confirmCouponSelection" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
            <text class="btn-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 地址选择弹窗 -->
    <view class="address-modal" v-if="showAddressModal" @click="closeAddressModal" :style="{'--primary-color': themeColorStyles.primaryColor, '--primary-color-rgb': themeColorStyles['--primary-color-rgb']}">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择收货地址</text>
          <view class="close-btn" @click="closeAddressModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="address-list">
          <!-- 加载状态 -->
          <view v-if="loading && addressList.length === 0" class="loading-state">
            <text class="loading-text">加载地址中...</text>
          </view>

          <!-- 地址列表 -->
          <view class="address-item" :class="{ 'selected': selectedAddressId === address.addressId }"
            v-for="address in addressList" :key="address.addressId" @click="selectAddress(address)">
            <view class="address-info">
              <view class="recipient-info">
                <text class="recipient-name">{{ address.receiverName }}</text>
                <text class="recipient-phone">{{ address.receiverPhone }}</text>
                <view class="default-tag" v-if="address.isDefault === '1'">
                  <text class="tag-text">默认</text>
                </view>
              </view>
              <text class="address-detail">{{ address.province }}{{ address.city }}{{ address.district }}{{
                address.detailAddress }}</text>
            </view>
            <view class="address-radio">
              <view class="radio-circle" :class="{ 'checked': selectedAddressId === address.addressId }">
                <view class="radio-dot" v-if="selectedAddressId === address.addressId"></view>
              </view>
            </view>
          </view>

          <!-- 空地址状态 -->
          <view class="empty-address" v-if="!loading && addressList.length === 0">
            <text class="empty-text">暂无收货地址</text>
            <view class="add-address-btn" @click="addNewAddress" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
              <text class="btn-text">添加地址</text>
            </view>
          </view>
        </view>

        <view class="modal-actions">
          <view class="cancel-btn" @click="closeAddressModal" :class="{ 'disabled': isUpdatingAddress }" :style="{background: themeColorStyles.primaryColorBg, color: themeColorStyles.primaryColor, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}">
            <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消</text>
          </view>
          <view class="confirm-btn" @click="confirmChangeAddress"
            :class="{ 'disabled': isUpdatingAddress || !selectedAddressId }" :style="{background: themeColorStyles.primaryColor, boxShadow: themeColorStyles.primaryColorShadow}">
            <text class="btn-text">{{ isUpdatingAddress ? '更新中...' : '确认更换' }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 物流详情弹窗 -->
    <view class="logistics-modal" v-if="showLogisticsModal" @click="closeLogisticsModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header" :style="{background: `linear-gradient(135deg, ${themeColorStyles.primaryColor} 0%, ${themeColorStyles.primaryColorLight} 100%)`}">
          <text class="modal-title">物流详情</text>
          <view class="close-btn" @click="closeLogisticsModal">
            <text class="close-icon">×</text>
          </view>
        </view>

        <view class="logistics-info" v-if="logisticsDetail">
          <!-- 基本信息 -->
          <view class="basic-info">
            <view class="info-item">
              <text class="info-label">快递公司：</text>
              <text class="info-value">{{ logisticsDetail.com_name || '暂无信息' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">运单号：</text>
              <text class="info-value">{{ logisticsDetail.nu || '暂无信息' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">客服电话：</text>
              <text class="info-value">{{ logisticsDetail.tel || '暂无信息' }}</text>
            </view>
            <view class="info-item" v-if="logisticsDetail.delivery_time">
              <text class="info-label">预计送达：</text>
              <text class="info-value">{{ logisticsDetail.delivery_time }}</text>
            </view>
          </view>

          <!-- 物流跟踪详情 -->
          <view class="tracking-section" v-if="logisticsDetail.data && logisticsDetail.data.length > 0">
            <view class="section-title">
              <text class="title-text">物流跟踪</text>
            </view>
            <view class="tracking-list">
              <view class="tracking-item" v-for="(item, index) in logisticsDetail.data" :key="index"
                :class="{ 'first-item': index === 0 }">
                <view class="tracking-dot">
                  <view class="dot" :class="{ 'active': index === 0 }"></view>
                  <view class="line" v-if="index < logisticsDetail.data.length - 1"></view>
                </view>
                <view class="tracking-content">
                  <text class="tracking-context">{{ item.context }}</text>
                  <view class="tracking-meta">
                    <text class="tracking-time">{{ item.time }}</text>
                    <text class="tracking-address" v-if="item.address">{{ item.address }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 无物流信息提示 -->
          <view class="no-data" v-else>
            <text class="no-data-text">暂无物流跟踪信息</text>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-state" v-else>
          <text class="loading-text">加载中...</text>
        </view>
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import { getOrderDetail, getUserOrder, listUserOrderWithProducts, getOrderDetailByNo, updateOrderStatus, checkCommentStatus, updateOrderAddress, getLogisticsByOrderNo, getOrderItems } from '@/api/order'
import { getAddressByUserId } from '@/api/address'
import { getUserCouponList, useCoupon } from '@/api/coupon'
import { updateProductSaleCount, updateSkuSaleCount } from '@/api/product'
import { API_CONFIG } from '@/api/config'
import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
import couponCache from '@/utils/couponCache'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/theme.js'
import { getUserInfo } from '@/utils/auth'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      orderNo: '',
      showPaymentModal: false,
      selectedPayment: 'wechat',
      loading: true,

      // 地址选择相关
      showAddressModal: false,
      addressList: [],
      selectedAddressId: null,
      isUpdatingAddress: false,

      // 优惠券相关
      showCouponModal: false,
      selectedCoupon: null,
      tempSelectedCoupon: null,
      availableCoupons: [],
      loadingCoupons: false,

      // 物流详情弹窗相关
      showLogisticsModal: false,
      logisticsDetail: null,

      orderInfo: {
        id: '',
        orderNo: '',
        createTime: '',
        payTime: '',
        shipTime: '',
        orderStatus: 1, // 添加orderStatus字段，默认为1（待付款）
        status: 'pending',
        statusText: '待付款',
        statusClass: 'pending',
        payMethod: '微信支付',
        goodsAmount: '0.00',
        shippingFee: '0.00',
        discountAmount: '0.00',
        totalAmount: '0.00',
        canCancel: false,
        canPay: false,
        canConfirm: false,
        canEvaluate: false,
        canRefund: false,
        canChangeAddress: false,
        address: {
          name: '张三',
          phone: '138****8888',
          detail: '北京市朝阳区三里屯街道工体北路8号院1号楼101室'
        },
        logistics: {
          company: '顺丰速运',
          trackingNumber: 'SF1234567890123',
          currentStatus: '快件已到达北京朝阳三里屯营业点',
          updateTime: '2023-12-02 09:30:00'
        },
        goodsList: [
          {
            id: 1,
            name: '时尚休闲T恤',
            spec: '白色 L码',
            price: '99.00',
            quantity: 1,
            image: '/static/images/product1.jpg'
          },
          {
            id: 2,
            name: '运动鞋',
            spec: '黑色 42码',
            price: '200.00',
            quantity: 1,
            image: '/static/images/product2.jpg'
          }
        ]
      },
      
      // 主题色相关
      themeColor: '1'
    };
  },

  computed: {
    hasActions() {
      return this.orderInfo.canCancel || this.orderInfo.canPay ||
        this.orderInfo.canConfirm || this.orderInfo.canEvaluate || this.orderInfo.canRefund;
    },
    
    // 主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor);
    },
    
    // 主题色样式
    themeColorStyles() {
      const primary = this.primaryColor;
      const rgb = this.hexToRgb(primary);
      
      return {
        '--primary-color': primary,
        '--primary-color-rgb': `${rgb.r}, ${rgb.g}, ${rgb.b}`,
        primaryColor: primary,
        primaryColorLight: this.lightenColor(primary, 20),
        primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        primaryColorBorder: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        primaryColorBg: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`
      };
    }
  },

  async onLoad(options) {
    console.log('🚀 [订单详情页] onLoad方法开始执行');
    console.log('🚀 [订单详情页] 接收到的参数:', options);
    
    // 开始页面加载
    this.startPageLoading()
    
    // 监听确认收货成功事件
    uni.$on('confirmOrderSuccess', this.handleConfirmOrderSuccess);
    
    try {
      // 初始化主题色
      await this.initThemeColor();
      this.markThemeLoaded()
      
      // 只接受orderNo参数
      const orderNoParam = options.orderNo;
      
      if (orderNoParam) {
        this.orderNo = orderNoParam;
        console.log('使用订单号参数:', this.orderNo);
        await this.loadOrderDetail();
        
        // 检查是否通过分享链接进入
        if (options.shared === '1') {
          // 用户通过分享链接进入订单详情页
          // 记录分享访问统计
          this.recordShareVisit(this.orderNo);
        }
        
        // 标记数据已加载
        this.markDataLoaded()
      } else {
        console.error('订单详情页面缺少订单号参数');
        uni.showToast({
          title: '订单号参数缺失',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
        this.forceCompletePageLoading()
      }
    } catch (error) {
      console.error('订单详情页面加载失败:', error)
      this.forceCompletePageLoading()
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载订单详情
    async loadOrderDetail() {
      try {
        this.loading = true

        // 使用统一的登录检测
        const loginResult = await checkLoginStatus()
        if (!loginResult.isLoggedIn) {
          this.loading = false
          return
        }

        let response;
        
        // 统一使用订单号查询订单详情
        if (this.orderNo) {
          console.log('使用订单号查询订单详情:', this.orderNo);
          response = await getOrderDetailByNo(this.orderNo);
        } else {
          throw new Error('缺少订单号(orderNo)参数');
        }

        console.log('订单详情API响应:', response);

        if (response.code === 200 && response.data && response.data.length > 0) {
          const orderData = response.data[0];
          const order = orderData.order;
          const items = orderData.items || [];

          console.log('解析到的订单数据:', order);
          console.log('解析到的商品数据:', items);

          // 设置订单基本信息
          this.orderInfo.id = order.orderId;
          this.orderInfo.orderNo = order.orderNo;
          this.orderInfo.createTime = order.createTime;
          this.orderInfo.payTime = order.payTime;
          this.orderInfo.shipTime = order.shipTime;

          // 设置金额信息
          this.orderInfo.goodsAmount = order.totalAmount || '0.00';
          this.orderInfo.shippingFee = order.freightAmount || '0.00';
          this.orderInfo.discountAmount = order.discountAmount || '0.00';
          this.orderInfo.totalAmount = order.paymentAmount || order.totalAmount || '0.00';

          // 设置收货地址
          this.orderInfo.address = {
            name: order.receiverName || '',
            phone: order.receiverPhone || '',
            detail: this.formatAddress(order) || ''
          };

          // 设置支付方式
          this.orderInfo.payMethod = order.paymentType || '微信支付';

          // 处理商品列表
          this.orderInfo.goodsList = items.map(itemData => {
            const orderItem = itemData.orderItem;
            const product = itemData.product;
            const sku = itemData.sku;

            // 处理订单商品项数据

            let spec = '';
            let displayName = orderItem.productName; // 默认使用订单项中的商品名称

            // 如果有SKU数据，优先使用SKU的名称和规格
            if (sku) {

              if (sku.skuName) {
                displayName = sku.skuName;
              }

              if (sku.specInfo) {
                try {
                  const specObj = JSON.parse(sku.specInfo);
                  spec = Object.entries(specObj).map(([key, value]) => `${key}: ${value}`).join(', ');

                } catch (e) {
                  spec = sku.specInfo;

                }
              }
            } else {
              // 如果没有SKU数据，尝试使用订单项中的规格信息
              try {
                if (orderItem.productSpec) {
                  const specObj = JSON.parse(orderItem.productSpec);
                  spec = Object.entries(specObj).map(([key, value]) => `${key}: ${value}`).join(', ');

                }
              } catch (e) {
                spec = orderItem.productSpec || '';

              }
            }

            // 处理图片URL，优先使用SKU图片，其次使用订单商品图片，最后使用商品主图
            let imageUrl = '';
            if (sku && sku.image) {
              // 七牛云存储，直接使用完整URL
              imageUrl = sku.image;
            } else if (orderItem.productImage) {
              // 七牛云存储，直接使用完整URL
              imageUrl = orderItem.productImage;
            } else if (product && product.mainImage) {
              // 七牛云存储，直接使用完整URL
              imageUrl = product.mainImage;
            }

            const result = {
              id: orderItem.orderItemId,
              name: displayName, // 使用SKU名称或订单项名称
              spec: spec,
              price: orderItem.productPrice,
              quantity: orderItem.productQuantity,
              image: imageUrl,
              productId: orderItem.productId,
              skuId: orderItem.skuId, // 添加SKU ID字段
              // 添加SKU相关字段供模板使用
              skuName: sku ? sku.skuName : null,
              skuImage: sku && sku.image ? sku.image : null, // 七牛云存储，直接使用完整URL
              skuSpecInfo: sku ? (typeof sku.specInfo === 'string' ? sku.specInfo : JSON.stringify(sku.specInfo)) : null,
              productName: orderItem.productName || orderItem.realProductName,
              realProductName: orderItem.realProductName
            };



            return result;
          });

          // 设置订单状态
          this.orderInfo.orderStatus = order.orderStatus; // 保存原始orderStatus
          this.updateOrderStatus(order.orderStatus);

          // 如果订单状态不为1（待付款），查询是否使用了优惠券
          if (parseInt(order.orderStatus) !== 1 && order.orderNo) {
            await this.loadUsedCoupon(order.orderNo, loginResult.orgId);
          }

          // 如果订单状态为3（待收货）或4（已完成），查询物流信息
          if ((parseInt(order.orderStatus) === 3 || parseInt(order.orderStatus) === 4) && order.orderNo) {
            await this.loadLogisticsInfo(order.orderNo, loginResult.userId);
          }

        } else {
          uni.showToast({
            title: '订单不存在',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        // console.error('获取订单详情失败:', error)
        await handleApiError(error)
      } finally {
        this.loading = false
      }
    },

    // 更新订单状态
    updateOrderStatus(status) {
      // 将状态转换为数字类型进行匹配
      const numStatus = parseInt(status);

      // 新的状态配置：1-待付款，2-待发货，3-待收货，4-已完成，5-已取消，6-已退款
      const statusConfig = {
        1: {
          status: 'pending',
          statusText: '待付款',
          statusClass: 'pending',
          statusColor: '#FF6B35',
          statusBgColor: 'linear-gradient(135deg, #FF6B35 0%, #F7931E 100%)',
          canCancel: true,
          canPay: true,
          canConfirm: false,
          canEvaluate: false,
          canRefund: false,
          canChangeAddress: true
        },
        2: {
          status: 'paid',
          statusText: '待发货',
          statusClass: 'paid',
          statusColor: '#10B981',
          statusBgColor: 'linear-gradient(135deg, #10B981 0%, #059669 100%)',
          canCancel: false,
          canPay: false,
          canConfirm: false,
          canEvaluate: false,
          canRefund: true,
          canChangeAddress: false
        },
        3: {
          status: 'shipped',
          statusText: '待收货',
          statusClass: 'shipped',
          statusColor: '#4A90E2',
          statusBgColor: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
          canCancel: false,
          canPay: false,
          canConfirm: true,
          canEvaluate: false,
          canRefund: false,
          canChangeAddress: false
        },
        4: {
          status: 'completed',
          statusText: '已完成',
          statusClass: 'completed',
          statusColor: '#8B5CF6',
          statusBgColor: 'linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%)',
          canCancel: false,
          canPay: false,
          canConfirm: false,
          canEvaluate: true,
          canRefund: false,
          canChangeAddress: false
        },
        5: {
          status: 'cancelled',
          statusText: '已取消',
          statusClass: 'cancelled',
          statusColor: '#6B7280',
          statusBgColor: 'linear-gradient(135deg, #6B7280 0%, #4B5563 100%)',
          canCancel: false,
          canPay: false,
          canConfirm: false,
          canEvaluate: false,
          canRefund: false,
          canChangeAddress: false
        },
        6: {
          status: 'refunded',
          statusText: '已退款',
          statusClass: 'refunded',
          statusColor: '#EF4444',
          statusBgColor: 'linear-gradient(135deg, #EF4444 0%, #DC2626 100%)',
          canCancel: false,
          canPay: false,
          canConfirm: false,
          canEvaluate: false,
          canRefund: false,
          canChangeAddress: false
        }
      }

      const config = statusConfig[numStatus] || statusConfig[1]


      // 更新订单状态信息
      Object.assign(this.orderInfo, config)


    },

    // 获取状态图标
    getStatusIcon(status) {
      const icons = {
        'pending': '💰',
        'paid': '📦',
        'shipped': '🚚',
        'completed': '✅',
        'cancelled': '❌',
        'refunded': '💸'
      };
      return icons[status] || '📋';
    },

    // 获取状态描述
    getStatusDesc(status) {
      const descs = {
        'pending': '请在24小时内完成支付',
        'paid': '商家正在准备您的商品',
        'shipped': '商品正在配送中，请耐心等待',
        'completed': '订单已完成，感谢您的购买',
        'cancelled': '订单已取消',
        'refunded': '订单已退款，款项将近期退回'
      };
      return descs[status] || '';
    },

    // 复制订单号
    copyOrderNo() {
      uni.setClipboardData({
        data: this.orderInfo.orderNo,
        success: () => {
          uni.showToast({
            title: '订单号已复制',
            icon: 'success'
          });
        }
      });
    },

    // 复制运单号
    copyTrackingNumber() {
      uni.setClipboardData({
        data: this.orderInfo.logistics.trackingNumber,
        success: () => {
          uni.showToast({
            title: '运单号已复制',
            icon: 'success'
          });
        }
      });
    },

    // 取消订单
    cancelOrder() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '取消中...' });
              const response = await updateOrderStatus(this.orderInfo.id, '5');
              uni.hideLoading();

              if (response.code === 200) {
                uni.showToast({
                  title: '订单已取消',
                  icon: 'success'
                });
                // 更新本地订单状态
                this.orderInfo.orderStatus = '5';
                this.updateOrderStatus('5');
              } else {
                uni.showToast({
                  title: response.msg || '取消失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 支付订单
    payOrder() {
      // 检查收货地址是否为空
      if (!this.orderInfo.address || !this.orderInfo.address.name || !this.orderInfo.address.phone || !this.orderInfo.address.detail) {
        uni.showModal({
          title: '提示',
          content: '请先填写或选择收货地址后再进行支付',
          showCancel: true,
          cancelText: '取消',
          confirmText: '去填写',
          success: (res) => {
            if (res.confirm) {
              // 跳转到地址管理页面
              uni.navigateTo({
                url: '/pages/address/list'
              });
            }
          }
        });
        return;
      }

      this.showPaymentModal = true;
      this.selectedPayment = 'wechat'; // 默认选择微信支付
    },

    // 选择支付方式
    selectPayment(method) {
      this.selectedPayment = method;
      // 添加震动反馈
      uni.vibrateShort();
    },

    // 关闭支付弹窗
    closePaymentModal() {
      this.showPaymentModal = false;
      this.selectedPayment = '';
    },

    // 确认支付
    async confirmPayment() {
      if (!this.selectedPayment) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        });
        return;
      }

      // 注释掉原有的支付逻辑
      /*
      const paymentNames = {
        'wechat': '微信支付',
        'alipay': '支付宝支付',
        'offline': '线下支付'
      };

      try {
        uni.showLoading({ title: '支付中...' });
        const response = await updateOrderStatus(this.orderInfo.id, '2');

        if (response.code === 200) {
          // 如果选择了优惠券，需要更新优惠券状态为已使用
          if (this.selectedCoupon) {
            try {
              const couponResponse = await useCoupon(this.selectedCoupon.userCouponId, this.orderInfo.orderNo);
              if (couponResponse.code === 200) {
                // 清除优惠券缓存，因为优惠券状态已变更
                const userId = uni.getStorageSync('userId');
                const orgId = uni.getStorageSync('orgId');
                couponCache.clearAllCouponCache(orgId, userId);
                console.log('优惠券状态更新成功，缓存已清除');
              } else {
                console.error('优惠券状态更新失败:', couponResponse.msg);
              }
            } catch (couponError) {
              console.error('更新优惠券状态时发生错误:', couponError);
            }
          }

          uni.hideLoading();
          this.closePaymentModal();

          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          // 更新本地订单状态
          this.orderInfo.orderStatus = '2';
          this.updateOrderStatus('2');
          
          // 销量更新已在后端updateOrderStatus接口中处理，无需前端重复调用
        } else {
          uni.hideLoading();
          this.closePaymentModal();
          uni.showToast({
            title: response.msg || '支付失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        this.closePaymentModal();
        uni.showToast({
          title: '支付失败，请重试',
          icon: 'none'
        });
      }
      */

      // 新的微信支付逻辑
      try {
        uni.showLoading({ title: '创建支付订单中...' });
        
        // 从config.js获取微信支付配置参数
        const { API_CONFIG } = await import('@/api/config');
        const { createWechatPayOrder } = await import('@/api/order');
        
        // 获取用户openId
        const openId = uni.getStorageSync('openId');
        
        if (!openId) {
          console.error('❌ openId为空，无法进行支付');
          uni.showToast({
            title: '用户openId不能为空，请重新登录',
            icon: 'error'
          });
          return;
        }
        
        // 准备支付参数
        const paymentData = {
          outTradeNo: this.orderInfo.orderNo, // 商户订单号
          description: `订单支付-${this.orderInfo.orderNo}`, // 商品描述
          totalAmount: Math.round(parseFloat(this.getFinalAmount()) * 100), // 支付金额（分）
          openid: openId, // 用户openId
          wechatAppId: API_CONFIG.WECHAT_APPID, // 微信小程序APPID（仅传递非敏感信息）
          orgId: API_CONFIG.ORG_ID // 组织ID（用于后端动态读取支付配置）
        };
        
        // 调用后端创建预支付订单接口
        
        const response = await createWechatPayOrder(paymentData);
        
        uni.hideLoading();
        
        if (response.code === 200) {
          
          // 调用uni.requestPayment发起支付
          const paymentParams = response.data;
          
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: paymentParams.timeStamp,
            nonceStr: paymentParams.nonceStr,
            package: paymentParams.packageVal,
            signType: paymentParams.signType,
            paySign: paymentParams.paySign,
            success: async (res) => {
              
              try {
                uni.showLoading({ title: '处理支付结果...' });
                
                // 更新订单状态为已支付
                const updateResponse = await updateOrderStatus(this.orderInfo.id, '2');
                
                if (updateResponse.code === 200) {
                  // 如果选择了优惠券，需要更新优惠券状态为已使用
                  if (this.selectedCoupon) {
                    try {
                      const couponResponse = await useCoupon(this.selectedCoupon.userCouponId, this.orderInfo.orderNo);
                      if (couponResponse.code === 200) {
                        // 清除优惠券缓存，因为优惠券状态已变更
                        const userId = uni.getStorageSync('userId');
                        const orgId = uni.getStorageSync('orgId');
                        couponCache.clearAllCouponCache(orgId, userId);
                        console.log('优惠券状态更新成功，缓存已清除');
                      } else {
                        console.error('优惠券状态更新失败:', couponResponse.msg);
                      }
                    } catch (couponError) {
                      console.error('更新优惠券状态时发生错误:', couponError);
                    }
                  }
                  
                  uni.hideLoading();
                  this.closePaymentModal();
                  
                  uni.showToast({
                    title: '支付成功',
                    icon: 'success'
                  });
                  // 更新本地订单状态
                  this.orderInfo.orderStatus = '2';
                  this.updateOrderStatus('2');
                  
                  // 销量更新已在后端updateOrderStatus接口中处理，无需前端重复调用
                  // await this.updateProductsSaleCount();
                } else {
                  uni.hideLoading();
                  uni.showToast({
                    title: '支付成功但订单状态更新失败',
                    icon: 'none'
                  });
                }
              } catch (error) {
                uni.hideLoading();
                console.error('支付成功后处理失败:', error);
                uni.showToast({
                  title: '支付成功但后续处理失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.log('=== 支付失败回调 ===');
              console.log('支付失败结果:', err);
              
              this.closePaymentModal();
              
              if (err.errMsg && err.errMsg.includes('cancel')) {
                uni.showToast({
                  title: '支付已取消',
                  icon: 'none'
                });
              } else {
                uni.showToast({
                  title: '支付失败，请重试',
                  icon: 'none'
                });
              }
            },
            complete: () => {
              console.log('=== 支付完成回调 ===');
            }
          });
        } else {
          console.error('预支付订单创建失败:', response.msg);
          uni.showToast({
            title: response.msg || '支付订单创建失败',
            icon: 'none'
          });
          this.closePaymentModal();
        }
        
      } catch (error) {
        uni.hideLoading();
        this.closePaymentModal();
        console.error('微信支付调用失败:', error);
        uni.showToast({
          title: '支付失败，请重试',
          icon: 'none'
        });
      }
    },

    // 确认收货
    async confirmOrder() {
      try {
        // 先查询微信发货状态，检查是否已确认收货
        uni.showLoading({ title: '检查订单状态中...' });
        
        const { queryShippingStatus } = await import('@/api/order');
        const statusResponse = await queryShippingStatus({
          orderNo: this.orderInfo.orderNo
        });
        
        console.log('=== 确认收货前检查微信状态 ===');
        console.log('订单号:', this.orderInfo.orderNo);
        console.log('微信状态查询响应:', statusResponse);
        
        uni.hideLoading();
        
        if (statusResponse.code === 200 && statusResponse.data) {
          const statusData = statusResponse.data;
          console.log('微信状态数据:', statusData);
          console.log('isConfirmed值:', statusData.isConfirmed);
          console.log('order_state值:', statusData.order_state);
          
          // 如果微信侧已确认收货（order_state >= 3），直接调用确认收货接口，不弹出微信组件
          if (statusData.success && statusData.isConfirmed) {
            console.log('微信侧已确认收货，直接调用确认收货接口');
            this.handleConfirmOrderCallback();
            return;
          }
          
          // 如果微信侧未确认收货，但本地订单状态已经是已完成(4)，说明可能存在状态不同步
          if (this.orderInfo.orderStatus === '4') {
            console.log('本地订单状态已完成，但微信侧未确认，可能存在状态不同步');
            uni.showModal({
              title: '提示',
              content: '订单状态可能存在不同步，是否重新刷新订单信息？',
              success: (res) => {
                if (res.confirm) {
                  this.loadOrderDetail();
                }
              }
            });
            return;
          }
        }
        
        // 如果微信侧未确认收货或查询失败，调用微信确认收货组件
        console.log('微信侧未确认收货，调用微信确认收货组件');
        const { fetchWxMerchantPublicInfo } = await import('@/api/order');
        let merchantId = null;
        try {
          const pubInfo = await fetchWxMerchantPublicInfo();
          merchantId = (pubInfo && pubInfo.data && (pubInfo.data.merchantId || pubInfo.data.mchId)) || null;
        } catch (e) {
          console.warn('获取商户ID失败，将仅使用订单号调用确认组件', e);
        }
        wx.openBusinessView({
          businessType: 'weappOrderConfirm',
          extraData: {
            merchant_id: merchantId,
            merchant_trade_no: this.orderInfo.orderNo
          },
          success: (res) => {
            console.log('微信确认收货组件调用成功:', res);
          },
          fail: (err) => {
            console.error('微信确认收货组件调用失败:', err);
            uni.showToast({
              title: '确认收货组件调用失败，请重试',
              icon: 'none'
            });
          }
        });
        
      } catch (error) {
        uni.hideLoading();
        console.error('查询订单发货状态失败:', error);
        
        // 查询失败时，仍然调用微信确认收货组件
        console.log('查询状态失败，调用微信确认收货组件');
        const { fetchWxMerchantPublicInfo } = await import('@/api/order');
        let merchantId = null;
        try {
          const pubInfo = await fetchWxMerchantPublicInfo();
          merchantId = (pubInfo && pubInfo.data && (pubInfo.data.merchantId || pubInfo.data.mchId)) || null;
        } catch (e) {
          console.warn('获取商户ID失败，将仅使用订单号调用确认组件', e);
        }
        wx.openBusinessView({
          businessType: 'weappOrderConfirm',
          extraData: {
            merchant_id: merchantId,
            merchant_trade_no: this.orderInfo.orderNo
          },
          success: (res) => {
            console.log('微信确认收货组件调用成功:', res);
          },
          fail: (err) => {
            console.error('微信确认收货组件调用失败:', err);
            uni.showToast({
              title: '确认收货组件调用失败，请重试',
              icon: 'none'
            });
          }
        });
      }
    },

    // 处理确认收货成功回调
    handleConfirmOrderSuccess(extraData) {
      console.log('确认收货成功回调:', extraData);
      // 调用确认收货接口
      this.handleConfirmOrderCallback();
    },

    // 处理微信确认收货组件的回调
    async handleConfirmOrderCallback() {
      try {
        console.log('=== 开始处理确认收货回调 ===');
        console.log('当前订单状态:', this.orderInfo.orderStatus);
        
        // 如果订单状态已经是已完成(4)，不需要重复调用
        if (this.orderInfo.orderStatus === '4') {
          console.log('订单状态已经是已完成，无需重复确认收货');
          uni.showToast({
            title: '订单已确认收货',
            icon: 'success'
          });
          return;
        }
        
        uni.showLoading({ title: '确认中...' });
        const response = await updateOrderStatus(this.orderInfo.id, '4');
        uni.hideLoading();

        if (response.code === 200) {
          console.log('确认收货接口调用成功');
          uni.showToast({
            title: '确认收货成功',
            icon: 'success'
          });
          // 更新本地订单状态
          this.orderInfo.orderStatus = '4';
          this.updateOrderStatus('4');
        } else {
          console.error('确认收货接口调用失败:', response.msg);
          uni.showToast({
            title: response.msg || '确认收货失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('确认收货处理异常:', error);
        uni.showToast({
          title: '确认收货失败，请重试',
          icon: 'none'
        });
      }
    },

    // 评价订单
    async evaluateOrder() {
      // 检查商品列表是否存在
      if (!this.orderInfo.goodsList || this.orderInfo.goodsList.length === 0) {
        uni.showToast({
          title: '商品信息异常',
          icon: 'none'
        });
        return;
      }

      try {
        // 检查是否已经评价过
        const response = await checkCommentStatus(
          this.orderInfo.id,
          this.orderInfo.goodsList[0].productId
        );

        if (response.code === 200 && response.data.hasCommented) {
          uni.showModal({
            title: '提示',
            content: '您已经评价过该商品，无法重复评价',
            showCancel: false
          });
          return;
        }
      } catch (error) {
        console.error('检查评价状态失败:', error);
      }

      // 跳转到评价页面，传递订单ID和商品ID
      uni.navigateTo({
        url: `/pages/order/evaluate?orderId=${this.orderInfo.id}&productId=${this.orderInfo.goodsList[0].productId}`
      });
    },

    // 申请退款
    refundOrder() {
      // 跳转到申请退款页面
      uni.navigateTo({
        url: `/pages/refund/apply?orderId=${this.orderInfo.id}&orderNo=${this.orderInfo.orderNo}`
      });
    },

    // 格式化地址
    formatAddress(order) {
      if (!order) return '';

      const parts = [];
      if (order.receiverProvince) parts.push(order.receiverProvince);
      if (order.receiverCity) parts.push(order.receiverCity);
      if (order.receiverDistrict) parts.push(order.receiverDistrict);
      if (order.receiverAddress) parts.push(order.receiverAddress);

      return parts.join('');
    },

    // 显示地址选择弹窗
    openAddressModal() {
      this.showAddressModal = true;
      this.loadAddressList();
    },

    // 关闭地址选择弹窗
    closeAddressModal() {
      this.showAddressModal = false;
    },

    // 加载地址列表
    async loadAddressList() {
      try {
        // 显示加载状态
        uni.showLoading({ title: '加载地址中...' })

        // 使用统一的登录检测
        const loginResult = await checkLoginStatus()
        if (!loginResult.isLoggedIn) {
          uni.hideLoading()
          return
        }

        const response = await this.getAddressByUserId()

        uni.hideLoading()

        if (response.code === 200) {
          this.addressList = response.data || []
          if (this.addressList.length === 0) {
            uni.showToast({
              title: '暂无收货地址',
              icon: 'none'
            })
          }
        } else {
          this.addressList = []
          uni.showToast({
            title: response.msg || '获取地址失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('获取地址列表失败:', error)
        this.addressList = []
        await handleApiError(error)
      }
    },

    // 选择地址
    selectAddress(address) {
      this.selectedAddressId = address.addressId;
    },

    // 确认更换地址
    async confirmChangeAddress() {
      if (!this.selectedAddressId) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return;
      }

      // 防止重复提交
      if (this.isUpdatingAddress) {
        return;
      }

      try {
        this.isUpdatingAddress = true;
        uni.showLoading({ title: '更新地址中...' });

        // 调用更新订单地址的API
        const response = await this.updateOrderAddress(this.orderInfo.id, this.selectedAddressId);

        uni.hideLoading();
        this.isUpdatingAddress = false;

        if (response.code === 200) {
          uni.showToast({
            title: '地址更新成功',
            icon: 'success',
            duration: 2000
          });

          // 重新加载订单详情
          await this.loadOrderDetail();
          this.closeAddressModal();
        } else {
          uni.showToast({
            title: response.msg || '更新失败',
            icon: 'none',
            duration: 3000
          });
        }
      } catch (error) {
        uni.hideLoading();
        this.isUpdatingAddress = false;
        console.error('更新地址失败:', error);

        let errorMsg = '更新失败，请重试';
        if (error.message && error.message.includes('timeout')) {
          errorMsg = '网络超时，请检查网络连接';
        } else if (error.message && error.message.includes('Network')) {
          errorMsg = '网络异常，请检查网络连接';
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 获取用户地址列表
    async getAddressByUserId(userId) {
      return await getAddressByUserId(userId);
    },

    // 更新订单地址
    async updateOrderAddress(orderId, addressId) {
      const userId = this.$store.state.user.id;
      return await updateOrderAddress(orderId, addressId, userId);
    },

    // 添加新地址
    addNewAddress() {
      this.closeAddressModal();
      uni.navigateTo({
        url: '/pages/address/edit'
      });
    },

    // 显示优惠券选择弹窗
    showCouponSelection() {
      this.tempSelectedCoupon = this.selectedCoupon; // 初始化临时选中的优惠券
      this.showCouponModal = true;
      this.loadAvailableCoupons();
    },

    // 关闭优惠券选择弹窗
    closeCouponModal() {
      this.showCouponModal = false;
      this.tempSelectedCoupon = null;
    },

    // 加载可用优惠券
    async loadAvailableCoupons() {
      try {
        this.loadingCoupons = true;

        // 使用统一的登录检测
        const loginResult = await checkLoginStatus();
        if (!loginResult.isLoggedIn) {
          this.loadingCoupons = false;
          return;
        }

        // 导入优惠券API
        const { getUserCouponList } = await import('@/api/coupon');

        // 获取用户优惠券列表
        const response = await getUserCouponList({
          useStatus: '0', // 未使用
          pageNum: 1,
          pageSize: 100
        });

        if (response.code === 200) {
          const allCoupons = response.rows || [];

          // 过滤可用优惠券
          this.availableCoupons = allCoupons.filter(coupon => {
            return this.isCouponAvailable(coupon);
          });
        } else {
          this.availableCoupons = [];
          uni.showToast({
            title: response.msg || '获取优惠券失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取优惠券失败:', error);
        this.availableCoupons = [];
        await handleApiError(error);
      } finally {
        this.loadingCoupons = false;
      }
    },

    // 加载已使用的优惠券
    async loadUsedCoupon(orderNo, orgId) {
      try {
        // 导入优惠券API
        const { getCouponByOrderNo } = await import('@/api/coupon');

        // 根据订单号查询优惠券
        const response = await getCouponByOrderNo(orderNo, orgId);

        if (response.code === 200 && response.data) {
          // 设置已使用的优惠券信息
          this.selectedCoupon = response.data;
          this.orderInfo.discountAmount = this.getCouponDiscountAmount(response.data);
          console.log('已加载订单使用的优惠券:', response.data);
        } else {
          // 没有使用优惠券
          this.selectedCoupon = null;
          console.log('该订单未使用优惠券');
        }
      } catch (error) {
        console.error('查询订单优惠券失败:', error);
        this.selectedCoupon = null;
      }
    },

    // 加载物流信息
    async loadLogisticsInfo(orderNo, userId) {
      try {
        console.log('开始查询物流信息:', orderNo);

        // 首先获取基本物流信息
        const basicResponse = await getLogisticsByOrderNo(orderNo, userId);

        if (basicResponse.code === 200 && basicResponse.data) {
          // 设置基本物流信息
          this.orderInfo.logistics = {
            company: basicResponse.data.logisticsCompanyName || '未知快递公司',
            trackingNumber: basicResponse.data.logisticsNo || '暂无运单号',
            currentStatus: '运输中',
            updateTime: basicResponse.data.updateTime || new Date().toLocaleString(),
            trackingDetails: [] // 初始化跟踪详情数组
          };



          console.log('物流信息加载成功:', this.orderInfo.logistics);
        } else {
          console.log('未找到物流信息');
          // 保持默认的物流信息显示
          this.orderInfo.logistics = {
            company: '暂无物流信息',
            trackingNumber: '暂无运单号',
            currentStatus: '等待发货',
            updateTime: '',
            trackingDetails: []
          };
        }
      } catch (error) {
        console.error('查询物流信息失败:', error);
        // 出错时显示默认信息
        this.orderInfo.logistics = {
          company: '查询失败',
          trackingNumber: '暂无运单号',
          currentStatus: '无法获取物流状态',
          updateTime: '',
          trackingDetails: []
        };
      }
    },

    // 判断优惠券是否可用
    isCouponAvailable(coupon) {
      if (!coupon) return false;

      // 检查优惠券状态（useStatus: '0'=未使用, '1'=已使用, '2'=已过期）
      if (coupon.useStatus !== '0') return false;

      // 检查有效期
      const now = new Date();
      const expireTime = new Date(coupon.expireTime);
      if (now > expireTime) return false;

      // 获取订单金额（不包含运费和已有优惠）
      const orderAmount = parseFloat(this.orderInfo.goodsAmount || 0);

      // 根据优惠券类型判断
      if (coupon.couponType === '0' || coupon.couponType === '1') { // 满减券或折扣券
        const minAmount = parseFloat(coupon.minAmount || 0);
        if (minAmount > 0 && orderAmount < minAmount) {
          return false; // 不满足最低消费金额
        }
      }

      // 所有条件都满足
      return true;
    },

    // 选择优惠券
    selectCoupon(coupon) {
      if (coupon && !this.isCouponAvailable(coupon)) {
        uni.showToast({
          title: '该优惠券不满足使用条件',
          icon: 'none'
        });
        return;
      }

      this.tempSelectedCoupon = coupon;
    },

    // 确认优惠券选择
    async confirmCouponSelection() {
      try {
        // 如果选择了优惠券，需要更新订单的实付金额
        if (this.tempSelectedCoupon) {
          const discountAmount = this.getCouponDiscountAmount(this.tempSelectedCoupon);
          const userId = this.$store.state.user.id;

          console.log('=== 应用优惠券到订单 ===');
          console.log('订单ID:', this.orderInfo.id);
          console.log('用户ID:', userId);
          console.log('优惠金额:', discountAmount);

          // 导入订单API
          const { applyCouponToOrder } = await import('@/api/order');

          // 调用API更新订单实付金额
          const response = await applyCouponToOrder(this.orderInfo.id, userId, discountAmount);

          if (response.code === 200) {
            console.log('优惠券应用成功');
            // 更新本地订单信息
            this.orderInfo.paymentAmount = response.data.paymentAmount;
            this.orderInfo.couponAmount = response.data.couponAmount;
          } else {
            console.error('优惠券应用失败:', response.msg);
            uni.showToast({
              title: response.msg || '优惠券应用失败',
              icon: 'none'
            });
            return;
          }
        }

        this.selectedCoupon = this.tempSelectedCoupon;
        this.closeCouponModal();

        if (this.tempSelectedCoupon) {
          uni.showToast({
            title: '优惠券应用成功',
            icon: 'success'
          });
        }
      } catch (error) {
        console.error('应用优惠券时发生错误:', error);
        uni.showToast({
          title: '优惠券应用失败，请重试',
          icon: 'none'
        });
      }
    },

    // 获取优惠券显示文本
    getCouponDisplayText(coupon) {
      if (!coupon) return '';

      // 直接使用数据库中的coupon_name字段
      return coupon.couponName || '优惠券';
    },

    // 获取优惠券类型文本
    getCouponTypeText(couponType) {
      const typeMap = {
        '0': '满减券',
        '1': '折扣券',
        '2': '无门槛券',
        '3': '无门槛券'
      };
      return typeMap[couponType] || '优惠券';
    },

    // 获取优惠券描述
    getCouponDescription(coupon) {
      if (!coupon) return '';

      // 根据实际数据判断优惠券类型并生成优惠力度说明
      if (coupon.discountRate && coupon.discountRate !== null) {
        // 折扣券：discountRate*10折
        const discountRate = parseFloat(coupon.discountRate) * 10;
        return `${discountRate}折`;
      } else if (coupon.couponAmount) {
        // 有金额的优惠券
        const couponAmount = parseFloat(coupon.couponAmount);
        const minAmount = parseFloat(coupon.minAmount || 0);

        if (minAmount > 0) {
          // 满减券：满minAmount减couponAmount
          return `满${minAmount}减${couponAmount}`;
        } else {
          // 无门槛券：无门槛减免couponAmount
          return `无门槛减免${couponAmount}元`;
        }
      } else {
        return '优惠券';
      }
    },

    // 计算优惠券折扣金额
    getCouponDiscountAmount(coupon) {
      if (!coupon) return 0;

      const orderAmount = parseFloat(this.orderInfo.goodsAmount || 0);

      // 根据实际数据判断优惠券类型，而不是仅依赖couponType字段
      if (coupon.discountRate && coupon.discountRate !== null) { // 有折扣率的是折扣券
        const discountRate = parseFloat(coupon.discountRate);
        return (orderAmount * (1 - discountRate)).toFixed(2);
      } else if (coupon.couponAmount) { // 有金额的是满减券或无门槛券
        return parseFloat(coupon.couponAmount).toFixed(2);
      } else {
        return 0;
      }
    },

    // 计算最终支付金额
    getFinalAmount() {
      // 优先使用订单的实付金额字段
      if (this.orderInfo.paymentAmount !== null && this.orderInfo.paymentAmount !== undefined) {
        return parseFloat(this.orderInfo.paymentAmount).toFixed(2);
      }

      // 如果没有实付金额，则从商品总额开始计算
      let finalAmount = parseFloat(this.orderInfo.goodsAmount || 0);

      // 加上运费
      if (this.orderInfo.shippingFee) {
        finalAmount += parseFloat(this.orderInfo.shippingFee);
      }

      // 减去总优惠金额
      const totalDiscount = parseFloat(this.getTotalDiscountAmount());
      if (totalDiscount > 0) {
        finalAmount -= totalDiscount;
      }

      return Math.max(0.01, finalAmount).toFixed(2);
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },

    // 获取优惠券金额显示
    getCouponAmountDisplay() {
      // 优先显示订单中已保存的优惠券金额
      if (this.orderInfo.couponAmount && parseFloat(this.orderInfo.couponAmount) > 0) {
        return parseFloat(this.orderInfo.couponAmount).toFixed(2);
      }

      // 如果当前选择了优惠券，显示计算出的优惠金额
      if (this.selectedCoupon) {
        return this.getCouponDiscountAmount(this.selectedCoupon);
      }

      // 默认显示0.00
      return '0.00';
    },

    // 获取已使用的优惠券信息
    getUsedCouponInfo() {
      // 如果订单状态不是待支付，优先返回查询到的优惠券信息
      if (this.orderInfo.orderStatus != 1) {
        // 如果通过loadUsedCoupon查询到了优惠券信息，直接返回
        if (this.selectedCoupon) {
          return this.selectedCoupon;
        }
        // 否则，如果有优惠券金额，说明已使用了优惠券但查询失败
        if (this.orderInfo.couponAmount && parseFloat(this.orderInfo.couponAmount) > 0) {
          return {
            couponName: '已使用优惠券',
            couponAmount: this.orderInfo.couponAmount,
            couponType: '0' // 默认为满减券类型
          };
        }
      }
      return null;
    },

    // 获取总优惠金额（优先显示优惠券金额，避免重复计算）
    getTotalDiscountAmount() {
      // 优先显示优惠券金额
      const couponAmount = parseFloat(this.getCouponAmountDisplay());
      if (couponAmount > 0) {
        return couponAmount.toFixed(2);
      }

      // 如果没有优惠券，显示其他优惠金额
      if (this.orderInfo.discountAmount && parseFloat(this.orderInfo.discountAmount) > 0) {
        return parseFloat(this.orderInfo.discountAmount).toFixed(2);
      }

      return '0.00';
    },

    // 显示物流详情弹窗
    async showLogisticsDetail() {
      this.showLogisticsModal = true;
      this.logisticsDetail = null;

      try {
        // 调用物流跟踪API
        const { getLogisticsTracking } = await import('@/api/order');
        const response = await getLogisticsTracking(this.orderInfo.orderNo);

        if (response.code === 200 && response.data) {
          this.logisticsDetail = response.data.data;
          console.log('API响应数据:', response);
          console.log('物流详情数据:', this.logisticsDetail);
          console.log('物流跟踪数据:', this.logisticsDetail.data);
        } else {
          uni.showToast({
            title: response.msg || '获取物流信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取物流详情失败:', error);
        uni.showToast({
          title: '获取物流信息失败',
          icon: 'none'
        });
      }
    },

    // 关闭物流详情弹窗
    closeLogisticsModal() {
      this.showLogisticsModal = false;
      this.logisticsDetail = null;
    },

    // 更新商品销量
    async updateProductsSaleCount() {
      try {
        console.log('开始更新商品销量...');
        
        // 优先使用goodsList，如果没有则调用API获取订单商品列表
        let itemsToUpdate = [];
        
        if (this.orderInfo.goodsList && this.orderInfo.goodsList.length > 0) {
          // 使用已加载的商品列表
          itemsToUpdate = this.orderInfo.goodsList;
          console.log('使用已加载的商品列表，商品数量:', itemsToUpdate.length);
        } else {
          // 调用API获取订单商品列表
          try {
            console.log('调用API获取订单商品列表，订单ID:', this.orderInfo.orderId);
            const userInfo = await getUserInfo();
            const response = await getOrderItems(this.orderInfo.orderId, userInfo.userId);
            if (response.code === 200 && response.data && response.data.length > 0) {
              itemsToUpdate = response.data;
              console.log('API获取商品列表成功，商品数量:', itemsToUpdate.length);
            } else {
              console.log('API返回的商品列表为空');
              return;
            }
          } catch (error) {
            console.error('获取订单商品列表失败:', error);
            return;
          }
        }
        
        // 更新每个商品的销量和SKU销量
        for (const item of itemsToUpdate) {
          const productId = item.productId || item.product_id;
          const skuId = item.skuId || item.sku_id;
          const quantity = item.quantity || item.num || 1;
          
          // 更新商品销量
          if (productId) {
            try {
              console.log('更新商品销量，商品ID:', productId);
              const response = await updateProductSaleCount(productId);
              if (response.code === 200) {
                console.log('商品销量更新成功，商品ID:', productId);
              } else {
                console.error('商品销量更新失败，商品ID:', productId, '错误:', response.msg);
              }
            } catch (error) {
              console.error('更新商品销量时发生错误，商品ID:', productId, '错误:', error);
            }
          }
          
          // 更新SKU销量
          if (skuId) {
            try {
              console.log('更新SKU销量，SKU ID:', skuId, '数量:', quantity);
              const skuResponse = await updateSkuSaleCount(skuId, quantity);
              if (skuResponse.code === 200) {
                console.log('SKU销量更新成功，SKU ID:', skuId);
              } else {
                console.error('SKU销量更新失败，SKU ID:', skuId, '错误:', skuResponse.msg);
              }
            } catch (error) {
              console.error('更新SKU销量时发生错误，SKU ID:', skuId, '错误:', error);
            }
          }
        }
      } catch (error) {
        console.error('更新商品销量失败:', error);
      }
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          // console.log('异步获取主题色 - 订单详情页面:', themeColor)
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          // console.log('同步获取主题色 - 订单详情页面:', themeColor)
        }
      } catch (error) {
        // console.error('订单详情页面主题色初始化失败:', error)
        // 使用默认主题色
        this.themeColor = '1'
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 };
    },
    
    // 颜色变亮
    lightenColor(color, percent) {
      const rgb = this.hexToRgb(color);
      const amount = Math.round(2.55 * percent);
      const r = Math.min(255, rgb.r + amount);
      const g = Math.min(255, rgb.g + amount);
      const b = Math.min(255, rgb.b + amount);
      return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    },
    
    // 记录外部链接访问统计
    recordShareVisit(orderNo) {
      try {
        // 记录外部链接访问统计
        console.log('订单外部链接访问统计已记录，订单号:', orderNo);
        
        // 这里可以调用后端API记录外部链接访问统计
        // 例如：
        // this.$http.post('/api/external/visit', {
        //   orderNo: orderNo,
        //   visitTime: new Date().toISOString(),
        //   source: 'external_link',
        //   type: 'order'
        // });
      } catch (error) {
        console.error('记录订单外部链接访问统计失败:', error);
      }
    }

  }

};
</script>

<style lang="scss" scoped>
.order-detail-page {
  background: linear-gradient(180deg, #F8FAFE 0%, #F2F6FC 100%);
  min-height: 100vh;
  padding-bottom: 120rpx;
}



/* 内容滚动区域 */
.content-scroll {
  height: calc(100vh - 120rpx);
  padding: 32rpx;
}

/* 卡片基础样式 */
.status-card,
.logistics-card,
.address-card,
.goods-card,
.order-info-card,
.cost-card,
.coupon-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: 1px solid rgba(74, 144, 226, 0.08);
}

.card-header {
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1px solid #F5F7FA;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

/* 订单状态卡片 */
.status-card {
  padding: 40rpx 32rpx;
  display: flex;
  align-items: center;
  color: #FFFFFF;
  transition: all 0.3s ease;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(74, 144, 226, 0.15);
  border: 2rpx solid rgba(74, 144, 226, 0.1);

  /* 默认样式 - 待收货 */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  /* 待付款状态 */
  &.pending {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.15);
  }

  /* 待发货状态 */
  &.paid {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.15);
  }

  /* 待收货状态 */
  &.shipped {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.15);
  }

  /* 已完成状态 */
  &.completed {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.15);
  }

  /* 已取消状态 */
  &.cancelled {
    background: linear-gradient(135deg, #8B9DC3 0%, #9EAEC7 100%);
    box-shadow: 0 4rpx 20rpx rgba(139, 157, 195, 0.15);
  }

  /* 已退款状态 */
  &.refunded {
    background: linear-gradient(135deg, #8B9DC3 0%, #9EAEC7 100%);
    box-shadow: 0 4rpx 20rpx rgba(139, 157, 195, 0.15);
  }
}

.status-icon-wrapper {
  margin-right: 32rpx;
}

.status-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

  .icon-text {
    font-size: 48rpx;
    color: #667eea;
  }
}

.status-info {
  flex: 1;
}

.status-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #FFFFFF;
  display: block;
  margin-bottom: 12rpx;
}

.status-desc {
  font-size: 28rpx;
  color: #FFFFFF;
  display: block;
}

/* 物流信息卡片 */
.logistics-content {
  padding: 32rpx;
}

.logistics-company {
  font-size: 28rpx;
  color: var(--primary-color, #4A90E2);
  font-weight: 500;
}

.logistics-number {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.label {
  font-size: 28rpx;
  color: #666666;
  margin-right: 16rpx;
}

.number {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  flex: 1;
}

.copy-btn {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  .copy-text {
    font-size: 24rpx;
  }
}

.logistics-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.update-time {
  font-size: 24rpx;
  color: #999999;
}

/* 查看详情按钮样式 */
.logistics-detail-btn {
  margin-top: 24rpx;
  padding: 20rpx 32rpx;
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.detail-btn-text {
  font-size: 28rpx;
  color: #FFFFFF;
  font-weight: 500;
  margin-right: 8rpx;
}

.detail-btn-arrow {
  font-size: 24rpx;
  color: #FFFFFF;
  font-weight: bold;
}

/* 物流跟踪详情样式 */
.logistics-tracking {
  margin-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.tracking-title {
  margin-bottom: 20rpx;
}

.title-text {
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
}

.tracking-list {
  position: relative;
}

.tracking-item {
  display: flex;
  margin-bottom: 30rpx;
  position: relative;
}

.tracking-item:last-child {
  margin-bottom: 0;
}

.tracking-dot {
  width: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20rpx;
}

.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background: #ddd;
  position: relative;
  z-index: 2;
}

.dot.active {
  background: var(--primary-color, #4A90E2);
  width: 20rpx;
  height: 20rpx;
}

.line {
  width: 2rpx;
  height: 50rpx;
  background: #eee;
  margin-top: 8rpx;
}

.tracking-content {
  flex: 1;
  padding-top: 2rpx;
}

.tracking-context {
  color: #333;
  font-size: 26rpx;
  line-height: 1.4;
  display: block;
  margin-bottom: 8rpx;
}

.first-item .tracking-context {
  color: var(--primary-color, #4A90E2);
  font-weight: 500;
}

.tracking-time {
  color: #999;
  font-size: 24rpx;
  display: block;
}

/* 收货地址卡片 */
.address-content {
  padding: 32rpx;
  display: flex;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.recipient-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.recipient-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-right: 24rpx;
}

.recipient-phone {
  font-size: 28rpx;
  color: #666666;
}

.address-detail {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.6;
}

.address-icon {
  margin-left: 24rpx;

  .icon {
    font-size: 48rpx;
  }
}

/* 商品信息卡片 */
.goods-count {
  font-size: 28rpx;
  color: #666666;
}

.goods-list {
  padding: 0 32rpx 32rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #F5F7FA;

  &:last-child {
    border-bottom: none;
  }
}

.goods-image-wrapper {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  overflow: hidden;
  margin-right: 24rpx;
  background: #F5F7FA;
}

.goods-image {
  width: 100%;
  height: 100%;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  display: block;
  margin-bottom: 12rpx;
  line-height: 1.4;
}

.goods-spec {
  font-size: 24rpx;
  color: #999999;
  display: block;
  margin-bottom: 16rpx;
}

.goods-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 32rpx;
  color: #4A90E2;
  font-weight: 600;
}

.goods-qty {
  font-size: 28rpx;
  color: #666666;
}

/* 订单信息卡片 */
.order-details {
  padding: 0 32rpx 32rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #F5F7FA;

  &:last-child {
    border-bottom: none;
  }
}

.detail-label {
  font-size: 28rpx;
  color: #666666;
}

.detail-value-wrapper {
  display: flex;
  align-items: center;
}

.detail-value {
  font-size: 28rpx;
  color: #1A1A1A;
  margin-right: 16rpx;
}

/* 费用明细卡片 */
.cost-details {
  padding: 0 32rpx 32rpx;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #F5F7FA;

  &:last-child {
    border-bottom: none;
  }

  &.total {
    padding-top: 32rpx;
    border-top: 2px solid #F5F7FA;
  }
}

.cost-label {
  font-size: 28rpx;
  color: #666666;

  .total & {
    font-size: 32rpx;
    font-weight: 600;
    color: #1A1A1A;
  }
}

.cost-value {
  font-size: 28rpx;
  color: #1A1A1A;

  &.discount {
    color: #FF6B35;
  }

  &.total-price {
    font-size: 36rpx;
    font-weight: 600;
    color: #4A90E2;
  }
}

/* 底部操作栏 */
.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  padding: 20rpx 32rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.04);
  border-top: 1px solid rgba(74, 144, 226, 0.08);
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.action-btn:active {
  transform: scale(0.95);
}

/* 主要按钮样式 */
.action-btn.primary {
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.3);
}

.action-btn.primary:active {
  box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.4);
}

/* 次要按钮样式 */
.action-btn.secondary {
  background: rgba(74, 144, 226, 0.1);
  color: #4A90E2;
  border: 1rpx solid rgba(74, 144, 226, 0.2);
}

.action-btn.secondary:active {
  background: rgba(74, 144, 226, 0.15);
}

.btn-text {
  font-size: 28rpx;
  font-weight: 500;
  display: block;
}

.bottom-space {
  height: 40rpx;
}

/* 支付弹窗样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
  animation: fadeIn 0.3s ease-out;
}

.modal-content {
  width: 100%;
  background: #FFFFFF;
  border-radius: 32rpx 32rpx 0 0;
  padding: 0;
  animation: slideUp 0.3s ease-out;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1px solid #F5F7FA;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.close-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: #F5F7FA;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    background: #E8F2FF;
    transform: scale(0.9);
  }
}

.close-icon {
  font-size: 40rpx;
  color: #8B9BB0;
  font-weight: 300;
}

.payment-methods {
  padding: 24rpx 32rpx;
}

.payment-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  margin-bottom: 16rpx;
  border-radius: 16rpx;
  border: 2rpx solid #F5F7FA;
  background: #FFFFFF;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.selected {
    border-color: var(--primary-color);
    background: rgba(var(--primary-color-rgb), 0.05);
    box-shadow: 0 4rpx 20rpx rgba(var(--primary-color-rgb), 0.1);
  }

  &:active {
    transform: scale(0.98);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.payment-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  background: #F8FAFE;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;

  .icon-text {
    font-size: 40rpx;
  }

  .payment-icon-img {
    width: 48rpx;
    height: 48rpx;
  }
}

.payment-info {
  flex: 1;
  margin-right: 24rpx;
}

.payment-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #1A1A1A;
  display: block;
  margin-bottom: 8rpx;
}

.payment-desc {
  font-size: 28rpx;
  color: #8B9BB0;
}

.payment-radio {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 3rpx solid #E5E7EB;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &.checked {
    border-color: var(--primary-color);
    background: var(--primary-color);
  }
}

.radio-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background: #FFFFFF;
  animation: radioScale 0.2s ease-out;
}

.payment-amount {
  padding: 24rpx 32rpx;
  border-top: 1px solid #F5F7FA;
  border-bottom: 1px solid #F5F7FA;
  background: #FAFBFC;
  display: flex;
  align-items: center;
  justify-content: center;
}

.amount-label {
  font-size: 32rpx;
  color: #666666;
  margin-right: 16rpx;
}

.amount-value {
  font-size: 40rpx;
  font-weight: 700;
  color: #FF6B35;
}

.modal-actions {
  padding: 32rpx;
  display: flex;
  gap: 24rpx;
}

.cancel-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  border: 2rpx solid #E5E7EB;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    background: #F5F7FA;
    transform: scale(0.98);
  }

  .btn-text {
    font-size: 32rpx;
    color: #666666;
    font-weight: 500;
  }
}

.confirm-btn {
  flex: 2;
  height: 88rpx;
  border-radius: 44rpx;
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 20rpx rgba(74, 144, 226, 0.3);

  &:active {
    background: linear-gradient(135deg, #357ABD 0%, #2E6BA8 100%);
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(74, 144, 226, 0.4);
  }

  &.disabled {
    background: #E5E7EB;
    box-shadow: none;

    .btn-text {
      color: #8B9BB0;
    }
  }

  .btn-text {
    font-size: 32rpx;
    color: #FFFFFF;
    font-weight: 600;
  }
}

/* 优惠券卡片样式 */
.coupon-card {
  .coupon-action {
    display: flex;
    align-items: center;
    cursor: pointer;

    &.disabled {
      cursor: not-allowed;
      opacity: 0.6;

      .coupon-text {
        color: #999999 !important;
      }
    }

    .coupon-text {
      font-size: 28rpx;
      color: #666666;
      margin-right: 16rpx;

      &.selected {
        color: #4A90E2;
        font-weight: 500;
      }
    }

    .arrow-icon {
      font-size: 32rpx;
      color: #CCCCCC;
      transform: rotate(0deg);
      transition: transform 0.3s ease;
    }
  }

  .coupon-info {
    padding: 16rpx 32rpx 24rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8rpx;

    .coupon-desc {
      font-size: 24rpx;
      color: #999999;
      line-height: 1.4;
    }

    .coupon-discount {
      font-size: 28rpx;
      color: #FF6B35;
      font-weight: 600;
      line-height: 1.2;
      margin-left: 16rpx;
    }
  }
}

/* 优惠券选择弹窗样式 */
.coupon-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 9999;
  animation: fadeIn 0.3s ease;

  .modal-content {
    width: 100%;
    max-height: 80vh;
    background: #FFFFFF;
    border-radius: 32rpx 32rpx 0 0;
    animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    display: flex;
    flex-direction: column;

    .modal-header {
      padding: 32rpx;
      border-bottom: 1px solid #F5F7FA;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .modal-title {
        font-size: 36rpx;
        font-weight: 600;
        color: #1A1A1A;
      }

      .close-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .close-icon {
          font-size: 40rpx;
          color: #999999;
        }
      }
    }

    .coupon-list {
      flex: 1;
      overflow-y: auto;
      padding: 0 32rpx;

      .loading-state,
      .empty-state {
        padding: 80rpx 0;
        text-align: center;

        .loading-text,
        .empty-text {
          font-size: 28rpx;
          color: #999999;
        }
      }

      .coupon-item {
        padding: 32rpx 0;
        border-bottom: 1px solid #F5F7FA;
        display: flex;
        align-items: center;
        cursor: pointer;
        transition: background-color 0.2s ease;

        &:last-child {
          border-bottom: none;
        }

        &.selected {
          background-color: rgba(var(--primary-color-rgb), 0.05);
        }

        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .coupon-info {
          flex: 1;

          .coupon-header {
            display: flex;
            align-items: center;
            margin-bottom: 8rpx;

            .coupon-title {
              font-size: 32rpx;
              font-weight: 600;
              color: #1A1A1A;
              margin-right: 16rpx;
            }

            .coupon-type {
              font-size: 20rpx;
              color: var(--primary-color);
              background: rgba(var(--primary-color-rgb), 0.1);
              padding: 4rpx 12rpx;
              border-radius: 8rpx;
            }
          }

          .coupon-desc {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            display: block;
          }

          .coupon-validity {
            font-size: 20rpx;
            color: #999999;
            display: block;
          }
        }

        .coupon-radio {
          margin-left: 24rpx;

          .radio-circle {
            width: 40rpx;
            height: 40rpx;
            border: 2rpx solid #CCCCCC;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;

            &.checked {
              border-color: var(--primary-color);
              background: var(--primary-color);
            }

            .radio-dot {
              width: 16rpx;
              height: 16rpx;
              border-radius: 50%;
              background: #FFFFFF;
              animation: radioScale 0.2s ease-out;
            }
          }
        }
      }
    }
  }
}

/* 动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }

  to {
    transform: translateY(0);
  }
}

@keyframes radioScale {
  0% {
    transform: scale(0);
  }

  100% {
    transform: scale(1);
  }
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  padding: 40rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #F3F4F6;
  border-top: 6rpx solid var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 24rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #8B9BB0;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 地址弹窗样式 */
.address-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
  animation: fadeIn 0.3s ease-out;
}

.address-list {
  padding: 24rpx 32rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.loading-state {
  text-align: center;
  padding: 60rpx 0;
  color: #666;
  font-size: 28rpx;
}

.address-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  margin-bottom: 16rpx;
  border-radius: 16rpx;
  border: 2rpx solid #F5F7FA;
  background: #FFFFFF;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.selected {
    border-color: var(--primary-color);
    background: rgba(var(--primary-color-rgb), 0.05);
    box-shadow: 0 4rpx 20rpx rgba(var(--primary-color-rgb), 0.1);
  }

  &:active {
    transform: scale(0.98);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.address-item .address-info {
  flex: 1;
  margin-right: 24rpx;
}

.address-item .recipient-info {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.address-item .recipient-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #1A1A1A;
  margin-right: 16rpx;
}

.address-item .recipient-phone {
  font-size: 28rpx;
  color: #666666;
  margin-right: 16rpx;
}

.default-tag {
  padding: 4rpx 12rpx;
  background: var(--primary-color);
  color: #FFFFFF;
  border-radius: 8rpx;
  font-size: 20rpx;
}

.tag-text {
  font-size: 20rpx;
  color: #FFFFFF;
}

.address-item .address-detail {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.4;
}

.address-radio {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .radio-circle {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #CCCCCC;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;

    &.checked {
      border-color: var(--primary-color);
      background: var(--primary-color);
    }

    .radio-dot {
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      background: #FFFFFF;
      animation: radioScale 0.2s ease-out;
    }
  }
}

.empty-address {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 24rpx;
  display: block;
}

.add-address-btn {
  margin-top: 20rpx;
  padding: 20rpx 40rpx;
  background: var(--primary-color);
  color: white;
  border-radius: 10rpx;
  font-size: 28rpx;
  display: inline-block;
  transition: all 0.3s ease;

  &:active {
    background: #357ABD;
    transform: scale(0.95);
  }
}

.add-address-btn .btn-text {
  color: #FFFFFF;
  font-size: 28rpx;
}

.modal-actions .disabled {
  opacity: 0.6;
  pointer-events: none;
}

.confirm-btn.disabled {
  background: #ccc !important;
  box-shadow: none !important;
}

.change-address-btn {
  padding: 8rpx 16rpx;
  background: rgba(var(--primary-color-rgb), 0.1);
  border-radius: 8rpx;
  border: 1px solid var(--primary-color);
  transition: all 0.3s ease;

  &:active {
    background: rgba(var(--primary-color-rgb), 0.15);
    transform: scale(0.95);
  }
}

.change-text {
  font-size: 24rpx;
  color: var(--primary-color);
}

/* 物流详情弹窗样式 */
.logistics-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 40rpx;
  box-sizing: border-box;
}

.logistics-modal .modal-content {
  background: #FFFFFF;
  border-radius: 24rpx;
  width: 100%;
  max-height: 80%;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
}

.logistics-modal .modal-header {
  padding: 32rpx;
  border-bottom: 1px solid #F5F7FA;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logistics-modal .modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}

.logistics-modal .close-btn {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(0.95);
  }
}

.logistics-modal .close-icon {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: bold;
}

.logistics-info {
  max-height: 60vh;
  overflow-y: auto;
  padding: 32rpx;
}

.basic-info {
  margin-bottom: 32rpx;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 16rpx 0;
  border-bottom: 1px solid #F8F9FA;
}

.info-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-label {
  font-size: 28rpx;
  color: #666666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  flex: 1;
}

.tracking-section {
  border-top: 1px solid #F0F0F0;
  padding-top: 32rpx;
}

.section-title {
  margin-bottom: 24rpx;
}

.section-title .title-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.logistics-modal .tracking-list {
  position: relative;
}

.logistics-modal .tracking-item {
  display: flex;
  margin-bottom: 32rpx;
  position: relative;
}

.logistics-modal .tracking-item:last-child {
  margin-bottom: 0;
}

.logistics-modal .tracking-dot {
  width: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.logistics-modal .dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background: #E5E5E5;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;
}

.logistics-modal .line {
  width: 2rpx;
  flex: 1;
  background: #E5E5E5;
  margin-top: 8rpx;
}

.logistics-modal .tracking-content {
  flex: 1;
  padding-top: 4rpx;
}

.logistics-modal .tracking-context {
  font-size: 28rpx;
  color: #1A1A1A;
  line-height: 1.5;
  margin-bottom: 8rpx;
  display: block;
  transition: all 0.3s ease;
  
  &.first-item {
    font-weight: 600;
  }
}

.tracking-meta {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.logistics-modal .tracking-time {
  font-size: 24rpx;
  color: #999999;
}

.tracking-address {
  font-size: 24rpx;
  color: #666666;
}

.no-data {
  text-align: center;
  padding: 80rpx 32rpx;
}

.no-data-text {
  font-size: 28rpx;
  color: #999999;
}

.loading-state {
  text-align: center;
  padding: 80rpx 32rpx;
}

.loading-state .loading-text {
  font-size: 28rpx;
  color: #666666;
}
</style>
